package com.dd.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dd.reggie.common.CustomException;
import com.dd.reggie.common.R;
import com.dd.reggie.entity.Category;
import com.dd.reggie.entity.Employee;
import com.dd.reggie.mapper.CategoryMapper;
import com.dd.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     *分页查询
     * @param page:初始页
     * @param pageSize:页面大小
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize){

        log.info("{},{},{}", page, pageSize);
        //1.构造分页构造器，用于分页查询
        Page pageInfo = new Page(page, pageSize);

        //2.构造条件构造器，给该对象添加各种条件
        //用于查询给定条件（name）的结果,应使用like模糊查询，以及排序条件等
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper();

        //3.添加过滤条件

        //4.添加排序条件,desc降序，asc升序
        queryWrapper.orderByAsc(Category::getSort);

        categoryService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }

    //返回页面的是下拉框数据，返回list
    //无论是新建菜品还是新建套餐里的选择分类，都使用此方法调用分类数据
    @GetMapping("/list")
    public R<List<Category>> list(Category category){

        log.info("type:{}", category.getType());

        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(queryWrapper);

        return R.success(list);
    }

    @PostMapping
    public R<String> save(@RequestBody Category category){
        log.info("category:{}", category);
        categoryService.save(category);
        return R.success("新增成功");
    }

    @DeleteMapping
    public R<String> delete(Long id){
        log.info("id:{}", id);
        //1.查询数据库是否存在该餐品
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getId, id);
        Category cat = categoryService.getOne(queryWrapper);

        //2.若不存在，返回错误信息
        if(cat == null){
            return R.error("删除失败");
        }

        //3.若存在，删除并返回响应
        categoryService.remove(id);
        return R.success("删除成功");
    }

    @PutMapping
    public R<String> updata(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改成功");
    }


}
